var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "react", "mobile/services/memberService", "mobile/services/userData", "maishu-ui-toolkit", "mobile/services/weixinService", "mobile/site"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const React = require("react");
    const memberService_1 = require("mobile/services/memberService");
    const userData_1 = require("mobile/services/userData");
    const ui = require("maishu-ui-toolkit");
    const weixinService_1 = require("mobile/services/weixinService");
    const site_1 = require("mobile/site");
    // let member = page.createService(MemberService);
    let userInfo = userData_1.userData.userInfo.value || {}; //await member.userInfo();
    class ValueSelector extends React.Component {
        constructor(props) {
            super(props);
            this.state = { value: this.props.value };
        }
        changeValue(item) {
            // this.state.value = item.value;
            this.setState({ value: item.value });
            if (this.valueChanged != null) {
                this.valueChanged(item);
            }
        }
        show() {
            this.element.style.removeProperty('display');
        }
        hide() {
            this.element.style.display = 'none';
        }
        render() {
            let value = this.state.value;
            let items = this.props.items;
            let title = this.props.title || '';
            return (React.createElement("div", { ref: (o) => this.element = this.element || o, style: { display: 'none' } },
                React.createElement("div", { className: "modal fade in", style: { display: 'block' }, onClick: () => { this.hide(); } },
                    React.createElement("div", { className: "list-group ", style: { position: 'absolute', bottom: 0, width: '100%' }, onClick: (e) => {
                            e.stopPropagation();
                        } },
                        React.createElement("div", { className: "list-group-item" },
                            React.createElement("span", { style: { fontWeight: 700 } }, title),
                            React.createElement("i", { className: "icon-remove pull-right", onClick: () => this.hide() })),
                        items.map(item => React.createElement("div", { key: item.name, className: "list-group-item", onClick: () => {
                                this.changeValue(item);
                                setTimeout(() => this.hide(), 200);
                            } },
                            React.createElement("span", null, item.name),
                            React.createElement("i", { className: "pull-right icon-ok", style: { display: value == item.value ? 'block' : 'none' } }))))),
                React.createElement("div", { className: "modal-backdrop fade in" })));
        }
    }
    class UserInfoPage extends React.Component {
        constructor(props) {
            super(props);
            this.state = { userInfo };
            this.member = this.props.createService(memberService_1.MemberService);
        }
        showGenderSelector() {
            this.genderSelector.show();
        }
        saveUserInfo() {
            this.state.userInfo.HeadImageUrl = this.imageBox.state.imageSource;
            return this.member.saveUserInfo(this.state.userInfo).then(() => {
                userData_1.userData.userInfo.value = this.state.userInfo;
            });
        }
        /** 将图片文件转换为 base64 字符串 */
        imageFileToBase64(file) {
            return new Promise((resolve, reject) => {
                if (!(/image/i).test(file.type)) {
                    console.log("File " + file.name + " is not an image.");
                    reject();
                }
                var reader = new FileReader();
                reader.readAsArrayBuffer(file);
                reader.onload = (ev) => {
                    var blob = new Blob([event.target['result']]);
                    var blobURL = URL.createObjectURL(blob);
                    var image = new Image();
                    let width = 100;
                    let height = 100;
                    image.style.width = `${width}px`;
                    image.style.height = `${height}px`;
                    image.src = blobURL;
                    image.onload = () => {
                        var canvas = document.createElement('canvas');
                        canvas.width = width;
                        canvas.height = height;
                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(image, 0, 0, width, height);
                        let data = canvas.toDataURL("/jpeg", 0.1);
                        resolve(data);
                    };
                };
            });
        }
        regionText(userInfo) {
            let region = "";
            // let userInfo = this.state.userInfo;
            if (userInfo.County) {
                region = userInfo.County;
            }
            if (userInfo.City) {
                region = userInfo.City + " " + region;
            }
            if (userInfo.Province) {
                region = userInfo.Province + " " + region;
            }
            return region;
        }
        showRegions() {
            // let r = this.state.receiptInfo;
            let userInfo = this.state.userInfo;
            let routeValues = {
                // province: { Id: userInfo.ProvinceId, Name: userInfo.Province },
                // county: { Id: userInfo.CountyId, Name: userInfo.CountyId },
                // city: { Id: userInfo.CityId, Name: userInfo.City },
                provinceId: userInfo.ProvinceId,
                provinceName: userInfo.Province,
                cityId: userInfo.CityId,
                cityName: userInfo.City,
                countyId: userInfo.CountyId,
                countyName: userInfo.County,
                selecteRegion: (province, city, county) => {
                    userInfo.City = city.Name;
                    userInfo.County = county.Name;
                    userInfo.Province = province.Name;
                    userInfo.CityId = city.Id;
                    userInfo.CountyId = county.Id;
                    userInfo.ProvinceId = province.Id;
                    this.setState(this.state);
                }
            };
            //TODO:改这里
            this.props.app.showPage("user_regions", routeValues);
        }
        componentDidMount() {
            this.genderSelector.valueChanged = (item) => {
                this.state.userInfo.Gender = item.value;
                this.setState(this.state);
            };
            // ui.renderImage(this.userImage);
        }
        render() {
            let userInfo = this.state.userInfo;
            let regionText = this.regionText(userInfo);
            return (React.createElement("div", null,
                React.createElement("header", null, site_1.defaultNavBar(this.props.source, { title: '用户信息' })),
                React.createElement("section", { className: "container" },
                    React.createElement("div", { className: "form-group" },
                        React.createElement("div", { className: "list-group" },
                            React.createElement("div", { className: "list-group-item row" },
                                React.createElement("div", { className: "col-xs-3" },
                                    React.createElement("label", { style: { position: 'relative', top: 30 } }, "\u5934\u50CF")),
                                React.createElement("div", { className: "col-xs-9" },
                                    React.createElement("div", { className: "pull-right", style: { paddingLeft: 10, position: 'relative', top: 30 } },
                                        React.createElement("i", { className: "icon-chevron-right" })),
                                    React.createElement(ImageBox, { ref: (e) => this.imageBox = e || this.imageBox, page: this.props.source, imageSource: userInfo.HeadImageUrl, imageText: "\u4E0A\u4F20\u5934\u50CF", imageClassName: "img-circle pull-right" }))),
                            React.createElement("div", { className: "list-group-item row" },
                                React.createElement("label", { className: "col-xs-3" }, "\u6635\u79F0"),
                                React.createElement("div", { "data-bind": "click:$root.edit('NickName'),tap:$root.edit('NickName')", className: "col-xs-9", style: { paddingLeft: 0 } },
                                    React.createElement("input", { className: "form-control", placeholder: "\u8BF7\u8F93\u5165\u6635\u79F0", style: { textAlign: 'right' }, value: userInfo.NickName || '', onChange: (e) => {
                                            this.state.userInfo.NickName = e.target.value;
                                            this.setState(this.state);
                                        } }))),
                            React.createElement("div", { className: "list-group-item row" },
                                React.createElement("label", { className: "col-xs-3" }, "\u6027\u522B"),
                                React.createElement("div", { className: "col-xs-9", style: { paddingLeft: 0, textAlign: 'right' } },
                                    React.createElement("span", { style: { color: 'gray' }, className: "form-control", onClick: () => {
                                            this.showGenderSelector();
                                        } },
                                        userInfo.Gender == 'Male' ? '男' : null,
                                        userInfo.Gender == 'Female' ? '女' : null,
                                        userInfo.Gender == 'None' || !userInfo.Gender ? '请选择性别' : null))),
                            React.createElement("div", { className: "list-group-item row" },
                                React.createElement("label", { className: "col-xs-3" }, "\u5730\u533A"),
                                React.createElement("div", { className: "col-xs-9", style: { paddingLeft: 0 }, onClick: () => this.showRegions() },
                                    React.createElement("div", { className: "pull-right", style: { paddingLeft: 10 } },
                                        React.createElement("i", { className: "icon-chevron-right" })),
                                    React.createElement("div", { className: "pull-right" }),
                                    React.createElement("div", { className: "pull-right text-danger pull-right" }, regionText ? regionText : "未填写"))))),
                    React.createElement("div", { className: "form-group" },
                        React.createElement("button", { className: "btn btn-success btn-block", ref: (e) => {
                                if (!e)
                                    return;
                                e.onclick = ui.buttonOnClick(() => this.saveUserInfo(), { toast: '用户信息保存成功' });
                            } }, "\u4FDD\u5B58")),
                    React.createElement(ValueSelector, { ref: (o) => this.genderSelector = o || this.genderSelector, items: [{ name: '男', value: 'Male' }, { name: '女', value: 'Female' }], value: userInfo.Gender, title: "\u8BF7\u9009\u62E9\u6027\u522B" }))));
        }
    }
    exports.default = UserInfoPage;
    class ImageBox extends React.Component {
        // private isWeixin: boolean;
        constructor(props) {
            super(props);
            this.state = { imageSource: this.props.imageSource };
            // var ua = navigator.userAgent.toLowerCase();
            // this.c
        }
        componentDidMount() {
            return __awaiter(this, void 0, void 0, function* () {
                ui.renderImage(this.imageElement);
                if (weixinService_1.isWeixin) {
                    let weixin = this.props.page.createService(weixinService_1.WeiXinService);
                    let wx = yield weixinService_1.createWeixinClient(weixin);
                    this.element.onclick = () => {
                        wx.chooseImage({
                            count: 1,
                            sizeType: ['compressed'],
                            sourceType: ["album"],
                            success: (res) => {
                                wx.getLocalImgData({
                                    localId: res.localIds[0],
                                    success: (res) => {
                                        var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                                        // this.state.imageSource = localData;;
                                        this.setState({ imageSource: localData });
                                    }
                                });
                            }
                        });
                    };
                }
            });
        }
        render() {
            let imageSource = this.state.imageSource;
            let imageText = this.props.imageText || '';
            return (React.createElement("div", { ref: (e) => this.element = e || this.element },
                React.createElement("img", { className: this.props.imageClassName, style: { width: 70, height: 70 }, src: imageSource, title: "\u4E0A\u4F20\u5934\u50CF", ref: (e) => this.imageElement = e || this.imageElement }),
                !weixinService_1.isWeixin ?
                    React.createElement("input", { type: "file", style: { position: 'absolute', top: 0, left: 0, opacity: 0, width: '100%', height: 90 }, accept: "images/*", multiple: false, onChange: (e) => {
                            let file = e.target.files[0];
                            if (!file)
                                return;
                            ui.imageFileToBase64(file, { width: 100, height: 100 }).then(data => {
                                // this.state.imageSource = data.base64;
                                this.setState({ imageSource: data.base64 });
                            });
                        } }) : null));
        }
    }
});
